import { getTemplate } from "@/api/service/template/template";
import { getThemeComponent } from "@/api/service/theme-coms/theme.coms";
import { downloadText } from "./utils";

export const useUploadFile = (accept?: string) => {
  const input = document.createElement("input");
  input.hidden = true;
  input.type = "file";
  input.accept = accept ?? "*";
  input.click();
  return new Promise<File>((res) => {
    input.onchange = () => {
      const { files } = input;
      if (files?.length === 1) {
        res(files[0]!);
      }
      input.remove();
    };
  });
};

export const toBase64 = (file: File) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  return new Promise<string>((res) => {
    reader.onload = () => {
      res(reader.result as string);
    };
  });
};

export const toText = (file: File) => {
  const reader = new FileReader();
  reader.readAsText(file);
  return new Promise<string>((res) => {
    reader.onload = () => {
      res(reader.result as string);
    };
  });
};

// 判断的是否是JSON字符串
export const isJson = (str: string): boolean => {
  try {
    const obj = JSON.parse(str);
    // 等于这个条件说明就是JSON字符串 会返回true
    if (typeof obj === "object" && obj) {
      return true;
    }
    // 不是就返回false
    return false;
  } catch (e) {
    return false;
  }
};
export const base64toFile = (base64String: string, filename: string): File => {
  // 解码base64字符串
  const byteCharacters = atob(base64String);
  const byteNumbers = new Array(byteCharacters.length);

  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);

  // 创建Blob对象
  const blob = new Blob([byteArray], { type: "application/octet-stream" });

  // 创建文件对象
  const file = new File([blob], filename, { type: "application/octet-stream" });

  return file;
};
/**
 * 安全解析包含大整数的 JSON 字符串
 * @param {string} jsonString - JSON 字符串
 * @returns {any} 解析后的对象，大整数会被转换为字符串
 */
export function safeJsonParse(jsonString: string) {
  try {
    try {
      // 仅处理resolutionId字段的数值类型，将其转换为带引号的字符串
      const processedJson = jsonString.replace(
        /"resolutionId":\s*(\d+)(?=[,\}])/g,
        '"resolutionId": "$1"'
      );

      // 解析处理后的JSON字符串
      return JSON.parse(processedJson);
    } catch (error) {
      console.error("JSON解析失败:", error);
      return null;
    }
  } catch (error) {
    console.error("JSON解析失败:", error);
    return null;
  }
}

/* 统一下载模板数据,传一个下载一个，传数组批量下载 */
export const downloadConfig = async (templateId: string, isLcd: boolean) => {
  if (!templateId) return;
  let templateData = "";
  if (isLcd) {
    const { data } = await getThemeComponent(templateId);
    templateData = data.templateData;
  } else {
    const { data } = await getTemplate(templateId);
    templateData = data.templateData;
  }

  downloadText(templateData, "config.json");
};
